<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\wework\middleware;
use think\facade\Db;

class usertoken
{
    protected $whiteList = [
        '/',
        '/wework/user/wechat/call',
        '/wework/staff/index',
        '/wework/user/moments/downexcel',
        '/wework/user/group/downexcel',
        '/wework/user/send/groupdownexcel',
        '/wework/user/send/downexcel',
        '/wework/user/lost/downexcel',
        '/wework/user/client/downexcel',
        '/wework/user/qr/downexcel',
        '/wework/user/qr/downexceltable',
        '/wework/user/data/customerdownexcel',
        '/wework/user/data/qrcodedownexcel',
        '/wework/user/data/groupdownexcel',
        '/wework/user/data/staffdownexcel',
        '/wework/user/moments/downexcellist',
        '/wework/satffcallback/index',
        '/wework/user/send/syncs',
        '/wework/user/moments/qysyncs',
        '/wework/user/send/groupsyncs',
        '/wework/user/group/groupsync',
        '/wework/customercallback/index',
        '/wework/customercallback/test',
        '/wework/user/staff/users',
        '/wework/user/client/customer',
        '/wework/job.staffjob/index'
    ];
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */

    public function handle($request, \Closure $next)
    {   
        $token = $request->header('UserToken');
        // echo app('http')->getName(); //获取应用名
        $url   = strtolower($request->baseUrl()); //获取url地址, 不带域名,然后小写,
        if(in_array($url,$this->whiteList) || preg_match("/^\/wework\/h5/", $url) || preg_match("/^\/wework\/job/", $url) || preg_match("/^\/wework\/satffcallback/", $url) || preg_match("/^\/wework\/customercallback/", $url)) return $next($request);
        if(!$token) return error('缺少参数UserToken');
        $user = Db::table('kt_base_user')->where([['token', '=', $token],['expire_time','>',time()]])->find();
        if(!$user) return error('无效的UserToken');
        Db::table('kt_base_user')->where('id',$user['id'])->update(['expire_time'=> time() + (7*24*3600) ]);
        return $next($request);
        
    }
}
